<!DOCTYPE html>
<html>
<head>
    <title>django-websocket</title>
    <meta charset="utf-8"/>

</head>
<body>
<br>
<input type="text" id="message" value="Hello, World!"/>
<button type="button" onclick="openws()">连接 websocket</button>
<button type="button" onclick="sendws()">发送 message</button>
<button type="button" onclick="closews()">关闭 websocket</button>
<h1>Received Messages</h1>
<div id="msg">

</div>
<script type="text/javascript">
    function openws() {
        if (window.s) {
            window.s.close()
        }
        /*创建socket连接*/
        var socket = new WebSocket("ws://127.0.0.1:8000/chat/echo/");
        socket.onopen = function (e) {
            console.log('WebSocket open');//成功连接上Websocket
            console.log(e);
        };
        socket.onmessage = function (e) {
            console.log('message: ' + e.data);//打印出服务端返回过来的数据
            var divmsg = document.getElementById('msg')
            divmsg.innerHTML = divmsg.innerHTML + '<p>' + e.data + '</p>';

        };
        // Call onopen directly if socket is already open
        if (socket.readyState == WebSocket.OPEN) {
            socket.onopen();
        }
        window.s = socket;
    }

    function sendws() {
        //如果未连接到websocket
        if (!window.s) {
            alert("websocket未连接.");
        } else {
            window.s.send(document.getElementById('message').value);
            //通过websocket发送数据
        }
    }

    function closews() {
        if (window.s) {
            window.s.close();  // 关闭websocket
            console.log('websocket已关闭');
        }
    }
</script>
</body>
</html>